//
//  AppDelegate.m
//  WeixinLoginDemo
//
//  Created by lanou3g on 16/4/8.
//  Copyright © 2016年 张静. All rights reserved.
//

#import "AppDelegate.h"
#import "WXApi.h"
#import "Macro.h"
@interface AppDelegate ()<WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [WXApi registerApp:kAppid withDescription:@"微信登录"];
    [self.window makeKeyAndVisible];
    self.wxDelegate =(id) self.window.rootViewController;
    return YES;
}
//跨应用跳转openurl
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
//    回调url传入WXApi
    [WXApi handleOpenURL:url delegate:self];
    return YES;
}
//微信服务器的响应
- (void)onResp:(BaseResp *)resp{
    NSLog(@"服务器返回数据:%@",resp);
//    用户授权码
    NSString *code = [(SendAuthResp *)resp code];
    [self requestAccessTokenWithCode:code];
}
//使用code换取accessToken
- (void)requestAccessTokenWithCode:(NSString *)code{
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid%@=APPID&secret%@=SECRET&code%@=CODE&grant_type=authorization_code",kAppid,kAppSecret,code];
//    进行网络请求
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:urlStr] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error && data) {
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"返回数据 %@",jsonDic);
           [self getUserInfoWithAccessToken:jsonDic[@"access_token"] OpenID:jsonDic[@"opedid"]];
        }
    }];
    [dataTask resume];
}
//通过accessToken和openID获取个人信息
- (void)getUserInfoWithAccessToken:(NSString *)token OpenID:(NSString *)openID{
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openID];
//    请求用户信息
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:urlStr] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error&&data) {
            NSDictionary *userInfo = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"用户信息:%@",userInfo);
            if ([self.wxDelegate respondsToSelector:@selector(wxLoginReceiveDict:)]) {
                [self.wxDelegate wxLoginReceiveDict:userInfo];
            }
        }
    }];
    [dataTask resume];
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
